 package 进阶.线程.线程安全.Demo04_Lock;

 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;

 public class RunnableImpl implements Runnable {


    /*
    * 1.在成员位置创建一个ReentrantLock对象
    * 2.在代码前调用lock
    * 3.代码后调用unlock
    * */

    private int t = 300;
    //1.
    Lock l = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            //2.
            l.lock();
           show();
           //3.
            //把unlock写到finally中，更好
        }
    }



    public  void show(){
        if(t > 0){
            try {
                Thread.sleep(10);
                System.out.println("卖出了第"+ t + "张票");
                t --;
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                l.unlock();
            }

        }
    }
}
